package base.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DTO.User;

/**
 * This servlet is for ServletContext getResource method testing. As the aboce
 * reason , only doPost methd is working.
 * 
 * 在這個測試中 主要是測試 ClassLoader.getResourceAsStream() 所能拿到的 Resource 和
 * ServletContext 可以拿到的 Resource 之間的差異。
 * 
 * 結論: 利用 ClassLoader 僅可以拿取 Container 預設 ClassPath下的資源
 * 換句話說:就是只拿的到WEb-INF下classes的資源。 而 ServletContext 就可以在取用這個 web application
 * 的所有資源，不侷限在WEB-INF/classes 之下。
 */
public class ContextTestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ContextTestServlet() {
	super();
    }

    protected void doGet(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
	doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
	InputStream ins = null;
	// this.getClass().getClassLoader().getResourceAsStream(
	// "/propertyFiles/test.properties");
	// InputStream ins = this.getServletContext().getResourceAsStream(
	// "/WEB-INF/classes/base/controller/test.properties");
	ins = getClass().getClassLoader().getResourceAsStream("/propertyFiles/test.properties");
	// InputStream ins = this.getServletContext().getResourceAsStream(
	// "/WEB-INF/propertyFiles/test.properties");
	Properties props = new Properties();
	props.load(ins);
	String name = props.getProperty("name");
	request.setAttribute("name", name);

	User user = new User();
	user.setAccount(request.getParameter("account"));
	user.setPassword(request.getParameter("password"));
	user.setAlias(request.getParameter("alias"));

	Map paramMap = new HashMap();
	paramMap.put("account", request.getParameter("account"));
	paramMap.put("user", user);

	request.setAttribute("user", user);
	request.setAttribute("paramMap", paramMap);

	Cookie cookie_1 = new Cookie("1", "testing");
	response.addCookie(cookie_1);

	RequestDispatcher requestDispatcher = request
		.getRequestDispatcher("/WEB-INF/views/second.jsp");
	requestDispatcher.forward(request, response);
    }

}
